/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
   Module Name          : com.yaodian100.ec.jd.batch.JdSyncOrder
   Module Description   :

   Date Created      : 2011/11/10
   Original Author   : cut7man
   Team              : yaodian100
   ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
   MODIFICATION HISTORY
   ------------------------------------------------------------------------------
   Date Modified       Modified by       Comments
   ------------------------------------------------------------------------------
   ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
package com.yaodian100.ec.jd.batch;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.commons.lang.time.DateUtils;
import org.hibernate.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.security.context.SecurityContextHolder;
import org.springframework.security.providers.UsernamePasswordAuthenticationToken;

import com.jd.ac.sdk.api.JdException;
import com.yaodian100.core.admin.entity.User;
import com.yaodian100.core.common.service.BaseManager;
import com.yaodian100.core.common.utils.StringUtils;
import com.yaodian100.core.menu.entity.Option;
import com.yaodian100.ec.jd.JDSerivce;

/**
 * @author cut7man
 * 
 */
public class JdSyncOrder {
	protected Logger logger = LoggerFactory.getLogger(getClass());
	private static SessionFactory sessionFactory;
	protected static ClassPathXmlApplicationContext ctx = null;
	private JDSerivce jdService;
	private BaseManager baseMgr;

	public static void main(String args[]) {
		String type = null;
		String startDateStr = null;
		String endDateStr = null;
		Date startDate = null;
		Date endDate = null;
		if (args != null && args.length >= 2) {
			startDateStr = args[0];
			endDateStr = args[1];
			SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmm");
			try {
				startDate = sdf.parse(startDateStr);
				endDate = sdf.parse(endDateStr);
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		Integer page = null;
		if (args != null && args.length == 3) {
			page = Integer.valueOf(args[2]);
		}

		ctx = new ClassPathXmlApplicationContext(new String[] { "applicationContext.xml", "applicationContext-*.xml" });
		String username = System.getenv("USERNAME");
		if (StringUtils.isBlank(username)) {
			username = System.getenv("USER");
		}
		if (StringUtils.isBlank(username)) {
			username = "test00";
		}
		if (ctx != null && ctx.getBean("sessionFactory") != null) {
			sessionFactory = (SessionFactory) ctx.getBean("sessionFactory");
		}
		User tester = new User(username);
		SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(tester, "password"));

		JdSyncOrder jdSyncOrder = new JdSyncOrder();

		jdSyncOrder.execute(startDate, endDate, page);
	}

	public JdSyncOrder() {
		jdService = ctx.getBean(JDSerivce.class);
		baseMgr = ctx.getBean(BaseManager.class);
	}

	public void execute(Date cstartDate, Date cendDate, Integer cpage) {
		int page = 10;
		int pageSize = 20;
		// Date startDate = DateUtil.incrementMinutes(-180).getTime();
		Date now = new Date();
		// 预设抓20分钟前
		Date startDate = DateUtils.addMinutes(now, -32);
		Date endDate = DateUtils.addMinutes(now, -20);
		if (cstartDate != null) {
			startDate = cstartDate;
		}
		if (cendDate != null) {
			endDate = cendDate;
		}

		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

		String startDateStr = sdf.format(startDate);
		String endDateStr = sdf.format(endDate);

		Integer totalResult = 0;
		try {
			Object[] result = baseMgr.queryByHql("from Option where menu.key=? and code=?", new Object[] { "SystemValue",
					"360buy_idKey" });
			Option op = null;
			if (result != null && result.length > 0) {
				op = (Option) result[0];
			}
			if (op == null) {
				throw new RuntimeException("can't find id and key!");
			}
			jdService.setId(op.getMemo1());
			jdService.setKey(op.getMemo2());

			jdService.setJdMemberOptionKey("360buy_member");
			totalResult = jdService.findBuyTimeJDOrderNew(startDateStr, endDateStr, "WAIT_SELLER_STOCK_OUT", String
					.valueOf(1), String.valueOf(pageSize));
			page = totalResult / pageSize + 1;
		} catch (JdException e) {
			e.printStackTrace();
			logger.warn(e.getMessage());
		}
		if (cpage != null) {
			page = cpage;
		}
		for (int i = 2; i <= page; i++) {
			try {
				jdService.findBuyTimeJDOrderNew(startDateStr, endDateStr, "WAIT_SELLER_STOCK_OUT", String.valueOf(i), String
						.valueOf(pageSize));
			} catch (JdException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				logger.warn(e.getMessage());
			}// 等待出货
		}
	}
}
